package com.wj.graph;

import com.wj.linear.Queue;

/**
 * @author wen.jie
 * @date 2021/8/27 13:43
 * bfs:广度优先遍历
 */
public class BreadthFirstSearch {

    //索引代表顶点，值代表当前顶点是否已经被搜索
    private boolean[] marked;
    //记录有多少顶点与s顶点相通
    private int count;
    //用来存储待搜索邻接表的点
    private Queue<Integer> waitSearch;

    public BreadthFirstSearch(Graph G, int s) {
        this.marked = new boolean[G.V()];
        this.waitSearch = new Queue<>();
        bfs(G, s);
    }

    //广度优先搜索找出G图中v顶点的所有相通顶点
    private void bfs(Graph G, int v) {
        count++;
        marked[v] = true;
        //入队列,待搜索
        waitSearch.enqueue(v);
        while (!waitSearch.isEmpty()) {
            //出队列
            Integer wait = waitSearch.dequeue();
            for (Integer w : G.adj(wait)) {
                if (!marked[w]) {
                    waitSearch.enqueue(w);
                    marked[w] = true;
                    count++;
                }
            }
        }
    }

    //判断w顶点与s顶点是否相通
    public boolean marked(int w){
        return marked[w];
    }

    //获取与顶点s相通的所有顶点的总数
    public int count() {
        return this.count;
    }

}
